package kr.co.sdsway2.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import kr.co.sdsway2.comm.DBUtil;
import kr.co.sdsway2.vo.AvatarVO;

public class RemoconDAO {

	public AvatarVO selectAvatarByPk(String avatarId) {
		Connection conn =null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		AvatarVO avatarVO = null;
		String queryStr = "select AVATAR_ID, LEFT_POSITION, RIGHT_POSITION from AVATAR where AVATAR_ID=?";
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(queryStr);
			System.out.println("query str : "+queryStr);
			System.out.println("avatarId : "+avatarId);
			ps.setString(1, avatarId);
			rs = ps.executeQuery();
			
			while(rs.next()){
				avatarVO = new AvatarVO();
				avatarVO.setAvatarId(rs.getString(1));
				avatarVO.setLeftPosition(rs.getString(2));
				avatarVO.setRightPosition(rs.getString(3));
			}
			return avatarVO;
		} catch (Exception e) {
			System.err.println("[ERROR] DB 오류 발생 ");
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		
		return avatarVO;
	}

	public void updateAvatarPosition(String avatarId, String direction,
			String distance) {
		
		Connection conn =null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		AvatarVO avatarVO = null;
		String queryStr = null;
		String updateStatement_queryStr = "";
		int resultCnt = -1;
		
		if("U".equals(direction)){
			updateStatement_queryStr = "top_position = top_position - 10 ";
		}else if("D".equals(direction)){
			updateStatement_queryStr = "top_position = top_position + 10 ";
		}else if("L".equals(direction)){
			updateStatement_queryStr = "left_position = left_position -10 ";
		}else if("R".equals(direction)){
			updateStatement_queryStr = "left_position = left_position +10 ";
		}
		queryStr = "update AVATAR set " + updateStatement_queryStr +" where avatar_id = ?";
		
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(queryStr);
			System.out.println("query str : "+queryStr);
			System.out.println("avatarId : "+avatarId);
			ps.setString(1, avatarId);
			resultCnt = ps.executeUpdate();
			
		} catch (Exception e) {
			System.err.println("[ERROR] DB 오류 발생 ");
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		
		if(resultCnt==1){
			System.out.println("avatar Position update success!");
		}else{
			System.err.println("[ERROR] DB 업데이트 도중 에러 발생");
		}
	}

}
